package com.example.service;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class SimpleUserDetailsService implements UserDetailsService {

    private List<User> userList;

    public SimpleUserDetailsService(){
        userList = new ArrayList<>(10);
        User user;
        String username, password;
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        for (int i = 0; i < 10; i++) {
            username = "user" + (i+1);
            password = encoder.encode("password" + (i+1));
            user = new User(username, password, Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
            userList.add(user);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> optionalUser = userList.stream().filter(user -> user.getUsername().equals(username)).findFirst();
        return optionalUser.orElseThrow(()->new UsernameNotFoundException("用户[" + username + "]不存在！"));
    }
}
